#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <event.h>
#include <signal.h>
#include "server.h"
#include "workthread.h"
#include "hashtable.h"
#include "list.h"
#include "functions.h"

int verbose=0;

int totalconncount=0;
int totalrequestcount=0;

pthread_mutex_t connlistlock=PTHREAD_MUTEX_INITIALIZER;

char policy_file[300]={0};

//*
void setnonblocking(int sock) {
	int opts;
	opts = fcntl(sock, F_GETFL);
	if (opts < 0) {
		printf("fd:%d\n",sock);
		perror("fcntl(sock,GETFL)");
		return;
	}
	opts = opts | O_NONBLOCK;
	if (fcntl(sock, F_SETFL, opts) < 0) {
		perror("fcntl(sock,SETFL,opts)");
		return;
	}
}
//*/
struct event_base* base;
struct event timer_ev;
struct timeval tv;
/*
void release_sock_event(struct event * ev)
{
	if(ev!=NULL){
		event_del(ev);
		free(ev);
	}
}
*/
/*
void on_write(int sock, short event, void* arg)
{
    char* buffer = (char*)arg;
    send(sock, buffer, strlen(buffer)+1, 0);
    printf("on_write\n");
    free(buffer);
}
*/

void addrequest(int fd,char * buffer,int size){
	totalrequestcount++;
	raw_request_t * req = (raw_request_t*) malloc(sizeof(raw_request_t));
	memset(req, 0, sizeof(raw_request_t));
	req->fd = fd;
	strncpy(req->buffer, buffer,size>sizeof(req->buffer)-1?sizeof(req->buffer)-1:size);
	//printf("receive data:%s\n", req->buffer);
	list_push_tail(req, g_requestlist);
}

void on_read(int fd, short event, void* arg)
{
	connection_t *conn=getconnectionfromfd(fd);
	if(conn!=NULL){
		time(&(conn->activetime));
	}

    int size;
    char buffer[MAXBUFFERLEN];
    bzero(buffer, MAXBUFFERLEN);
    //char c;

    int n=0,i=0;
    //大于MAXBUFFERLEN的数据，只保留最后收到的
    do{
    	bzero(buffer, MAXBUFFERLEN);
    	size=read(fd,buffer,MAXBUFFERLEN-1);
    	n+=size;
    }while(size==MAXBUFFERLEN-1);

    if(n==0){
		//printf("用户主动断开 %d\n",fd);
    	pthread_mutex_lock(&connlistlock);
		closeconnection(fd);
		pthread_mutex_unlock(&connlistlock);
		return;
    }
    if(n<3) return; //无效数据
    const char* pfreq = "<policy-file-request/>";
    if(n==strlen(pfreq)+1 && strcmp(buffer, pfreq)==0){
		n=write(fd,policy_file,strlen(policy_file)+1);
		//printf("发送policy-file-request完成\n");
    }else{
    	int istart=0;
    	for(i=0;i<size;i++){
    		if(buffer[i]=='\n'){
    			addrequest(fd,&buffer[istart],i-1);
    			istart=i+1;
    		}
    	}
    }
}

void on_accept(int fd, short event, void* arg)
{
    struct sockaddr_in cli_addr;
    int newfd;
    socklen_t sin_size;
    sin_size = sizeof(struct sockaddr_in);
    newfd = accept(fd, (struct sockaddr*)&cli_addr, &sin_size);

    if(newfd<0){
    	perror("connfd<0");
    	return;
    }

    totalconncount++;
	setnonblocking(newfd);

	connection_t * conn=malloc(sizeof(connection_t));
	bzero(conn,sizeof(connection_t));
	conn->fd=newfd;
	conn->read_ev=(struct event*)malloc(sizeof(struct event));
	time(&conn->activetime);
	char fds[10]={0};
	sprintf(fds,"%d",newfd);
	node_t * node=list_push_tail(conn,g_connectionlist);
	hash_insert(fds,node,g_connectiontable);

	event_set(conn->read_ev, newfd, EV_READ|EV_PERSIST, on_read, conn->read_ev);
	event_base_set(base, conn->read_ev);
	event_add(conn->read_ev, NULL);
	//printf("accept connection\n");

}

void on_timer(int fd, short event, void *argc){
	//printf("timer wakeup\n");
	//检测连接是否超时
	time_t t;
	time(&t);


	pthread_mutex_lock(&connlistlock);
	node_t * node=g_connectionlist->head;
	while(node!=NULL){
		connection_t * conn=node->data;
		if(t-conn->activetime>60*5){//超过5分钟没有动作的判断为死链
			printf("Close Death Connection:%d\n",conn->fd);
			node_t * node1=node->next;
			//unlock_list(g_connectionlist);
			closeconnection(conn->fd);
			//lock_list(g_connectionlist);
			node=node1;
		}else{
			node=node->next;
		}
	}
	pthread_mutex_unlock(&connlistlock);


	event_add(&timer_ev, &tv); // reschedule timer
}

void usage(){
	printf("-t <threadcount>    Set work thread count,default 20\n"
		   "-p <port>           Set Listen Port,default 5000\n"
		   "-d                  Start with Deamon\n"
		   "-h                  Show This Help\n"
		   "\n"
		   "Write by XUGP 2011,qhsoft@gmail.com\n"
	);
}

static void sig_handler(const int sig) {
    //printf("SIGINT handled.\n");
    exit(EXIT_SUCCESS);
}

int main(int argc, char* argv[])
{
	int c;
	int threadcount=20;
	int serverport=SERV_PORT;
	
    int do_daemonize = 0;
    char *allowdomain="*";

	/* handle SIGINT */
    signal(SIGINT, sig_handler);
	
	while((c=getopt(argc,argv,"t:hp:d"))!=-1){
		switch(c){
		case 't':
			threadcount=atoi(optarg);
			break;
		case 'h':
			usage();
            exit(EXIT_SUCCESS);
		case 'v':
			verbose=1;
			break;
		case 'p':
			serverport=atoi(optarg);
			break;
		case 'd':
			do_daemonize = 1;
			break;
		default:
			fprintf(stderr, "Illegal argument \"%c\"\n", c);
			return 1;
		}
	}

	/* daemonize if requested */
    /* if we want to ensure our ability to dump core, don't chdir to / */
    if (do_daemonize==1) {
        if (sigignore(SIGHUP) == -1) {
            perror("Failed to ignore SIGHUP");
        }
        if (daemonize(0, 0) == -1) {
            fprintf(stderr, "failed to daemon() in order to daemonize\n");
            exit(EXIT_FAILURE);
        }
    }

	init(threadcount);
	const char * pf = "<?xml version=\"1.0\"?>\n<cross-domain-policy>\n<site-control permitted-cross-domain-policies=\"all\"/>\n<allow-access-from domain=\"%s\" secure=\"false\" to-ports=\"%d\"/>\n</cross-domain-policy>";
	sprintf(policy_file,pf,allowdomain,serverport);

    struct sockaddr_in my_addr;
    int sock;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    int yes = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
    memset(&my_addr, 0, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(serverport);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    int ret=bind(sock, (struct sockaddr*)&my_addr, sizeof(struct sockaddr));
    if(ret==-1){
    	printf("Port be Used\n");
		exit(EXIT_FAILURE);
    }

    listen(sock, LISTENQ);
	printf("Server Started,ThreadCount:%d,port:%d!!!\n",threadcount,serverport);

	struct event listen_ev;

    base = event_base_new();
    event_set(&listen_ev, sock, EV_READ|EV_PERSIST, on_accept, NULL);
    event_base_set(base, &listen_ev);
    event_add(&listen_ev, NULL);
    event_set(&timer_ev,-1,0,on_timer,NULL);
    event_base_set(base,&timer_ev);

    tv.tv_sec=30;
    tv.tv_usec=0;
    event_add(&timer_ev,&tv);
    event_base_dispatch(base);

	
    return 0;

}
